package Login;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username=req.getParameter("username");
        String password=req.getParameter("password");

        //验证用户名和密码是否正确
        //正常用户名和密码是在数据库中存储的
        //但是此处为了简便，直接写死
        //我们假设用户名合法的为zhangsan和lisi
        //密码都是123
        if(!username.equals("zhangsan") && !username.equals("lisi"))
        {
            //登录失败
            System.out.println("登录失败，用户名错误");
            resp.sendRedirect("login.html");
            return;
        }
        if(!password.equals("123"))
        {
            //登录失败
            System.out.println("登录失败，密码错误");
            resp.sendRedirect("login.html");
            return;
        }
        //登录成功
        //1.创建一个会话
        HttpSession session= req.getSession(true);
        //2.把当前用户名保存在会话中
        session.setAttribute("username",username);
        //3.重定向到主页
        resp.sendRedirect("index");
    }
}
